use std::io::{Write, Read};
use std::fs::File;

/// 文件 / 文件夹是否存在
pub fn is_exist(path: &str) -> bool {
    match std::fs::metadata(path).ok() {
        Some(_) => true,
        None => false,
    }
}

/// 读文件内容
pub fn read(path: &str) -> anyhow::Result<String> {
    let mut s = String::new();
    File::open(path)?.read_to_string(&mut s)?;
    Ok(s)
}

/// 写文件内容
pub fn write(path: &str, bs: &[u8]) -> anyhow::Result<usize> {
    Ok(File::create(path)?.write(bs)?)
}

/// 把集合写进文件
pub fn write_from_t<'a, T>(path: &str, t: &T) -> anyhow::Result<usize>
    where T: serde::Serialize + 'a {

    let s = serde_json::to_string(t)?;
    Ok(write(path, s.as_bytes())?)
}